<script setup lang="ts">
import {
  useMessage,
  NForm,
  NFormItem,
  NInput,
  type FormInst,
  NButton,
  NIcon,
  NDatePicker,
  NSelect,
  type DataTableColumns,
  // useDialog,
  NDataTable,
  type SelectOption,
  type UploadFileInfo
} from 'naive-ui'
import { ref, shallowRef, h, onMounted } from 'vue'
import type {
  IdentifyApplyModel,
  IEOptionModel,
  CommonSelectOptionModel,
  ApplyBatchInfoModel,
  ApplyCollectingTableRowModel
} from '@/api/batch'
import { sendRequest } from '@/utils/api'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import FixedAction from '@/components/FixedAction.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
import { ArrowRightAltFilled } from '@vicons/material'
import { useRoute } from 'vue-router'
// import UploadFile from '../../../common/UploadFile.vue'
import { useRouter } from 'vue-router'
import VUploader from '@/components/VUploader/VUploader.vue'

const route = useRoute()
const router = useRouter()
const isNew = !route.params.id
const routeReplace = useRouteReplace(route.query.redirect as string)
// const dialog = useDialog()
const message = useMessage()

const formInst = shallowRef<FormInst | null>(null)
const formData = ref({} as IdentifyApplyModel)
const submitLoading = ref(false)

const batchInfo = ref({} as ApplyBatchInfoModel)
const queryBatchInfo = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse<ApplyBatchInfoModel>>({
      module: 'batch',
      api: 'applyFormInfo',
      override: {
        params: {
          batchId: route.params.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    batchInfo.value = res.data
  } catch (error) {
    console.error(error)
  }
}

const handleSubmit = () => {
  if (submitLoading.value) return
  formInst.value?.validate(async (error) => {
    if (error) return

    try {
      submitLoading.value = true
      const [error, res] = await sendRequest<HttpResponse<IdentifyApplyModel>>({
        module: 'batch',
        api: 'identifyApply',
        override: {
          data: {
            ...formData.value,
            identifyType:
              itSelectOptions.value.find((e) => e.value === formData.value.identifyTypeCode)
                ?.name ?? null,
            batchId: route.params.id || batchId.value,
            // @ts-ignore
            identifyExpertIds: formData.value.identifyExpertIds.join(','),
            // @ts-ignore
            fileIds: fileList.value ? fileList.value.map((e) => e.file?.remoteId).join(',') : null,
            batchNumList: tableData.value
              .filter((e) => !deleteIds.value.includes(e.subItemId))
              .map((e) => ({
                itemId: e.subItemId,
                itemNum: 1,
                subItemIds: checkedSubItemModels.value
                  .filter((s) => s.itemId === e.subItemId)
                  .map((s) => s.subItemId)
              }))
              .filter((e) => e.subItemIds.length)
          }
        }
      })

      if (error) return message.error(error.message)
      if (res.code !== 0) return message.error(res.msg)
      message.success(res.msg)
      window.flags.flushBatch = true
      routeReplace()
    } catch (error) {
      console.log(error)
    } finally {
      submitLoading.value = false
    }
  })
}

// const handleDelete = (id: number) => {
//   dialog.warning({
//     title: '确认删除？',
//     positiveText: '确认',
//     negativeText: '取消',
//     onPositiveClick: async () => {
//       deleteIds.value.push(id)
//     }
//   })
// }

const ieSelectOptions = shallowRef<IEOptionModel[]>([])
const ieLoading = ref(false)
const queryIESelectOptions = async () => {
  try {
    ieLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<IEOptionModel[]>>({
      module: 'batch',
      api: 'ieSelect'
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    ieSelectOptions.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    ieLoading.value = false
  }
}

const itSelectOptions = shallowRef<CommonSelectOptionModel[]>([])
const itLoading = ref(false)
const queryITSelectOptions = async () => {
  try {
    itLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<CommonSelectOptionModel[]>>({
      module: 'batch',
      api: 'itSelect'
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    itSelectOptions.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    itLoading.value = false
  }
}

const tableData = ref<ApplyCollectingTableRowModel[]>([])
const tableLoading = ref(false)
const deleteIds = ref<number[]>([])
const checkedIds = ref<number[]>([])
const checkedSubItemModels = shallowRef<ApplyCollectingTableRowModel[]>([])
const handleUpdateCheckedIds: any = (ids: number[], rows: ApplyCollectingTableRowModel[]) => {
  checkedIds.value = ids
  checkedSubItemModels.value = []

  rows.forEach((r) => {
    const root = tableData.value.findIndex((e) => e.subItemId === r.subItemId) !== -1
    if (root) {
      //
    } else {
      checkedSubItemModels.value.push(r)
    }
  })
}
const queryTableData = async () => {
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<ApplyCollectingTableRowModel>>({
      module: 'batch',
      api: 'identifyItems',
      override: {
        params: {
          batchId: route.params.id,
          limit: 100000000
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    res.data.list.forEach((e) => (e.subItemCode = e.itemCode))
    res.data.list.forEach((e) => (e.subItemId = e.itemId))
    tableData.value = res.data.list
  } catch (error) {
    console.error(error)
  } finally {
    tableLoading.value = false
  }
}
const columns: DataTableColumns<ApplyCollectingTableRowModel> = [
  {
    type: 'selection'
  },
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    render: (e, index) => {
      if (!e.subItems || e.subItems.length === 0) return null
      return index + 1
    }
  },
  {
    title: '征集物品编码',
    key: 'subItemCode'
  },
  {
    title: '征集品名称',
    key: 'itemName'
  },
  {
    title: '类型',
    key: 'itemType'
  },
  {
    title: '征集方式',
    key: 'collectType'
  },
  {
    title: '移交人',
    key: 'transferUser'
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    render: (e) => [
      h(
        NButton,
        {
          color: '#6CB187',
          quaternary: true,
          size: 'small',
          style: {
            display: e.subItems?.length ? 'none' : 'inline-flex'
          },
          onClick: () => {
            router.push({
              name: 'collectDetail',
              params: {
                id: e.itemId
              },
              query: {
                type: 'detail',
                redirect: route.fullPath,
                subItemId: e.itemId,
                fromBatchEdit: 'true'
              }
            })
          }
        },
        { default: () => '详情' }
      )
    ]
  }
]
// 获取批次
const batchList = ref([])
const getBatchList = async () => {
  const [error, res] = await sendRequest({
    module: 'identify',
    api: 'batchList'
  })
  if (error) throw error
  if (res.code !== 0) throw new Error(res.msg)
  batchList.value = res.data
}
// 选择批次后获取列表数据
const batchId = ref()
const getTableData = async (val: any, info: any) => {
  batchId.value = val
  batchInfo.value.batchName = info.batchName
  batchInfo.value.description = info.description || ''
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<ApplyCollectingTableRowModel>>({
      module: 'batch',
      api: 'identifyItems',
      override: {
        params: {
          batchId: val,
          limit: 100000000
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    tableData.value = res.data.list
  } catch (error) {
    console.error(error)
  } finally {
    tableLoading.value = false
  }
}
onMounted(() => {
  getBatchList()
  if (!isNew) {
    Promise.allSettled([queryBatchInfo(), queryTableData()])
  }
  Promise.allSettled([queryIESelectOptions(), queryITSelectOptions()])
})

const fileList = ref<UploadFileInfo[]>([])
const handleUpdateFileList = (e: UploadFileInfo[]) => {
  fileList.value = e
  console.log(e)
}
</script>

<template>
  <div class="identity-apply">
    <div class="ia-title">鉴定流程</div>
    <div class="ia-card identity-flow">
      <div class="step finished">提交鉴定</div>
      <NIcon
        color="#6CB187"
        size="32"
      >
        <ArrowRightAltFilled />
      </NIcon>
      <div class="step">鉴定登记</div>
      <NIcon
        color="#6CB187"
        size="32"
      >
        <ArrowRightAltFilled />
      </NIcon>
      <div class="step">鉴定结束</div>
    </div>

    <div class="br"></div>

    <div class="ia-title">基本信息</div>
    <NForm
      :disabled="submitLoading"
      :model="formData"
      ref="formInst"
      label-placement="left"
      require-mark-placement="left"
      label-width="100rem"
      class="ia-card grid"
    >
      <NFormItem
        label="鉴定名称："
        path="identifyName"
        :rule="[
          { required: true, message: '鉴定名称为必填项，请输入', trigger: 'blur' },
          {
            trigger: ['blur', 'input'],
            message: '鉴定名称不能超过200字',
            validator: (_, value) => (value ? value.length <= 200 : true)
          }
        ]"
      >
        <NInput
          placeholder="请输入"
          v-model:value="formData.identifyName"
        />
      </NFormItem>
      <NFormItem
        label="鉴定日期："
        path="identifyTime"
        :rule="{ required: true, message: '鉴定日期为必填项，请选择', trigger: ['change', 'blur'] }"
      >
        <NDatePicker
          input-readonly
          placeholder="请选择"
          style="flex: 1"
          format="yyyy-MM-dd"
          v-model:formatted-value="formData.identifyTime"
        />
      </NFormItem>
      <NFormItem
        label="鉴定地点："
        path="identifyAddress"
        :rule="[
          { required: true, message: '鉴定地点为必填项，请输入', trigger: 'blur' },
          {
            trigger: ['blur', 'input'],
            message: '鉴定地点不能超过100字',
            validator: (_, value) => (value ? value.length <= 100 : true)
          }
        ]"
      >
        <NInput
          placeholder="请输入"
          v-model:value="formData.identifyAddress"
        />
      </NFormItem>
      <NFormItem
        label="鉴定类型："
        path="identifyTypeCode"
        :rule="{ required: true, message: '鉴定类型为必填项，请选择', trigger: ['change', 'blur'] }"
      >
        <NSelect
          :options="(itSelectOptions as unknown as SelectOption[])"
          label-field="name"
          placeholder="请选择"
          v-model:value="formData.identifyTypeCode"
        />
      </NFormItem>
      <NFormItem
        label="鉴定专家："
        path="identifyExpertIds"
        :rule="{
          required: true,
          message: '鉴定专家为必填项，请选择',
          type: 'array',
          trigger: ['change', 'blur']
        }"
      >
        <NSelect
          :options="(ieSelectOptions as unknown as SelectOption[])"
          multiple
          label-field="userName"
          value-field="id"
          placeholder="请选择"
          v-model:value="formData.identifyExpertIds"
        />
      </NFormItem>
      <NFormItem label="描述：">
        <NInput
          type="textarea"
          rows="1"
          placeholder="请输入"
          v-model:value="formData.identifyDescription"
        />
      </NFormItem>
      <NFormItem label="附件：">
        <VUploader
          style="flex: 1"
          :file-list="fileList"
          @update:file-list="handleUpdateFileList"
        />
        <!-- <UploadFile
          @finish="handleUploadFinish"
          @remove="handleUploadRemove"
        >
          <template #trigger="{ handleClick }">
            <n-button
              @click="handleClick"
              color="#6CB187"
              ghost
              size="small"
            >
              点击上传
            </n-button>
          </template>
        </UploadFile> -->
      </NFormItem>

      <!-- <span style="padding-left: 100rem">
        带
        <span style="color: #fd4a29">*</span>
        为必填项
      </span> -->
    </NForm>

    <div class="br"></div>

    <div class="ia-title">批次信息</div>
    <NForm
      inline
      disabled
      :show-feedback="false"
      label-placement="left"
      label-width="100rem"
      class="ia-card"
    >
      <NFormItem label="批次编号：">
        <NInput
          v-if="!isNew"
          placeholder="/"
          :value="batchInfo.batchCode"
        />
        <NSelect
          :disabled="false"
          v-else
          style="width: 200rem"
          placeholder="请选择"
          :options="batchList"
          label-field="batchCode"
          value-field="id"
          :value="batchInfo.batchCode"
          :on-update:value="getTableData"
        />
      </NFormItem>
      <NFormItem label="批次名称：">
        <NInput
          placeholder="/"
          :value="batchInfo.batchName"
        />
      </NFormItem>
      <NFormItem label="描述：">
        <NInput
          type="textarea"
          rows="1"
          placeholder="/"
          :value="batchInfo.description"
        />
      </NFormItem>
    </NForm>

    <div class="ia-card">
      <NDataTable
        :data="tableData.filter((e) => !deleteIds.includes(e.subItemId))"
        :columns="columns"
        :loading="tableLoading"
        children-key="subItems"
        :row-key="(row) => row.subItemId"
        :checked-row-keys="checkedIds"
        @update-checked-row-keys="handleUpdateCheckedIds"
        max-height="200rem"
        bordered
      />
    </div>
  </div>

  <FixedAction>
    <div class="identity-apply-buttons">
      <NButton
        color="#999999"
        ghost
        :disabled="submitLoading"
        @click="routeReplace"
      >
        取消
      </NButton>
      <NButton
        color="#5FB17F"
        :disabled="submitLoading"
        :loading="submitLoading"
        @click="handleSubmit"
      >
        确定
      </NButton>
    </div>
  </FixedAction>
</template>

<style scoped lang="scss">
.identity-apply {
  min-height: 100%;
  padding: 15rem 0 110rem;
  background-color: #f0efee;

  :deep(.n-data-table__pagination) {
    justify-content: flex-start;
  }

  .br {
    position: relative;
    width: 100%;
    padding: 30rem 0;

    &::after {
      content: '';
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      border-top: 1px dotted #bc9e70;
      transform: translateY(-50%);
    }
  }

  .ia-card {
    padding: 20rem;
    background-color: #e1e1e1;
  }

  .n-form.grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 0 60rem;
  }

  .ia-title {
    font-size: 26rem;
    margin-bottom: 30rem;
    color: #048c5e;
    line-height: 1;
  }

  .ia-table {
    display: flex;
    flex-direction: column;
    gap: 20rem 0;
    padding: 0 20rem 15rem;
  }

  .identity-flow {
    display: flex;
    align-items: center;
    gap: 0 1.5em;

    .step {
      padding: 10rem 15rem;
      background-color: #e1e1e1;

      &.finished {
        color: #fff;
        background-color: #6cb187;
      }
    }
  }
}

.identity-apply-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 16rem;

  .n-button {
    width: 100rem;
    height: 50rem;
  }
}
</style>
